/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.example;

import java.util.Collection;
import net.sourceforge.openforecast.*;
import net.sourceforge.openforecast.Observation;
import net.sourceforge.openforecast.models.MultipleLinearRegressionModel;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Collections;

/**
 *
 * @author Nadeeshani Hewage
 * Undergraduate: University of Moratuwa, Sri Lanka
 *
 */
public class MultipleLinearRegression {

    DataSet ds1, forecastedDS;
    DataPoint dp1;
    MultipleLinearRegressionModel forecaster;
    Hashtable result;
    String[] coefficients;
    String[][] output;

    String[] independantVariableNames;
    double[] dependantVariableValues;



    MultipleLinearRegression(double[][] yVariable, double[][] xVariable, String[][] xVarNames){

        independantVariableNames = new String[xVarNames[0].length];
                for(int i=0;i<xVarNames[0].length;i++){
                independantVariableNames[i]=xVarNames[0][i];
                }

        dependantVariableValues = new double[yVariable.length];
                for(int i=0;i<yVariable.length;i++){
                dependantVariableValues[i]=yVariable[i][0];
                }


        ds1= new DataSet();

        for (int i=0;i<dependantVariableValues.length;i++){
            dp1= new Observation(dependantVariableValues[i]);

            for(int j=0; j<independantVariableNames.length; j++){
                dp1.setIndependentValue(independantVariableNames[j],xVariable[i][j]);
            }
            ds1.add(dp1);
        }

        coefficients    = new String[independantVariableNames.length];           //string array for coefficients
	forecaster      = new MultipleLinearRegressionModel( independantVariableNames ); //MLReg Model

	// Initialize the model
	forecaster.init( ds1 );
        result= forecaster.getCoefficients();                           //get coefficients to the hashtable






    }


    String[][] returnResult(){                  //

        Collection col= result.values();        //read hashtable datapoint values to a collection
        ArrayList al = new ArrayList();
        al.addAll(col);
        Collections.reverse(al);


        output=new String[independantVariableNames.length+2][2];

        output[0][0]="Predictor";
        output[0][1]="Coefficient";
        output[1][0]="Constant";
        output[1][1]=forecaster.getIntercept()+"";
        int index=2;
        int k=0;
        
        Iterator it = al.iterator();

        while (it.hasNext()){

            output[index][0]=independantVariableNames[k];
            output[index][1]=it.next().toString();
            index++; k++;

        }


       return output;
    }




}
